﻿using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
using System;
using UnityEngine;

[Serializable, VolumeComponentMenu("Post-processing/Custom/OverriderSSR")]
public sealed class OverriderSSR : CustomPostProcessVolumeComponent, IPostProcessComponent
{
    [Tooltip("Controls the intensity of the effect.")]
    public ClampedFloatParameter intensity = new ClampedFloatParameter(0f, 0f, 1f);

    public ComputeShader overridersCS;

    public bool IsActive() => intensity.value > 0f;

    //public override CustomPostProcessInjectionPoint injectionPoint => CustomPostProcessInjectionPoint.BeforePostProcess;

    public override void Setup()
    {
        overridersCS = Resources.Load<ComputeShader>("OverriderSSRComputerShader");
        Debug.Log(injectionPoint);

        RenderTextureDescriptor rtd = new RenderTextureDescriptor(1920, 1080);//ARGB是用来存颜色通道的 这个图要传给shader 注意我们要a当遮罩 精度我认为单通道8字节足够了
        
        rtd.sRGB = false;
        rtd.enableRandomWrite = true;//绑定uav
        rtd.dimension = TextureDimension.Tex2DArray;
        rt = new RenderTexture(rtd);
        rt.Create();

        rtd.dimension = TextureDimension.Tex2D;
        rt2 = new RenderTexture(rtd);
        rt2.Create();
    }

    private RenderTexture rt,rt2;

    public override void Render(CommandBuffer cmd, HDCamera camera, RTHandle source, RTHandle destination)
    {
        if (overridersCS != null)
        {
            Debug.Log("进入后处理");
            //Shader.PropertyToID("_SsrHitPointTexture")
            //RTHandle ssr = camera.GetCurrentFrameRT(Shader.PropertyToID("_SsrHitPointTexture"));
            //Debug.Log(ssr.rt);

            int kernel = overridersCS.FindKernel("ScreenSpaceReflectionsReprojection");
            overridersCS.GetKernelThreadGroupSizes(kernel, out uint x, out uint y, out uint z);
            
            cmd.SetComputeTextureParam(overridersCS, kernel, Shader.PropertyToID("_TempTextureRW"), rt);
            cmd.SetComputeTextureParam(overridersCS, kernel, Shader.PropertyToID("_TempTextureRW2"), rt2);
            cmd.DispatchCompute(overridersCS, kernel, (int)(1920 / x), (int)(1080 / y), 1);

            cmd.SetGlobalTexture(Shader.PropertyToID("_SsrLightingTexture"), rt);
            
        }
        Debug.Log("渲染");
        //if (m_Material == null)
        //    return;

        //m_Material.SetFloat("_Intensity", intensity.value);
        //m_Material.SetTexture("_InputTexture", source);
        //HDUtils.DrawFullScreen(cmd, m_Material, destination);
    }

    public override void Cleanup()
    {
    }
}